<?php
namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use DB;
use App\Models\RoleUser;

class ApartmentController extends Controller
{
	public function apartmentApplication(Request $request) {
        if (!$request->isMethod('POST')) {
            return response()->json(['code' => 0, 'message' => '提交方式错误']);
        }
        $request_data = $request->input();

        if (!isset($request_data['unit_name']) || !$request_data['unit_name']) {
            return response()->json(['code' => 0, 'message' => '单位名称为必填项']);
        }
        if (!isset($request_data['unit_name_range']) || !$request_data['unit_name_range']) {
            return response()->json(['code' => 0, 'message' => '单位地区范围为必填项']);
        }
        // if (!isset($request_data['corporate_compliance']) || !$request_data['corporate_compliance']) {
        //     return response()->json(['code' => 0, 'message' => '法人代表为必填项']);
        // }
        // if (!isset($request_data['organization_code']) || !$request_data['organization_code']) {
        //     return response()->json(['code' => 0, 'message' => '组织机构代码为必填项']);
        // }
        // if (!isset($request_data['unit_nature']) || !$request_data['unit_nature']) {
        //     return response()->json(['code' => 0, 'message' => '单位性质为必填项']);
        // }
        if (!isset($request_data['field']) || !$request_data['field']) {
            return response()->json(['code' => 0, 'message' => '所属领域为必填项']);
        }
        if (!isset($request_data['contact_name']) || !$request_data['contact_name']) {
            return response()->json(['code' => 0, 'message' => '联系人为必填项']);
        }
        if (!isset($request_data['contact_phone']) || !$request_data['contact_phone']) {
            return response()->json(['code' => 0, 'message' => '联系电话为必填项']);
        }
        if (!isset($request_data['contact_address']) || !$request_data['contact_address']) {
            return response()->json(['code' => 0, 'message' => '联系地址为必填项']);
        }
        if (!isset($request_data['talent_category']) || !$request_data['talent_category']) {
            return response()->json(['code' => 0, 'message' => '人才类别为必填项']);
        }
        if (!isset($request_data['real_name']) || !$request_data['real_name']) {
            return response()->json(['code' => 0, 'message' => '真实姓名为必填项']);
        }
        if (!isset($request_data['phone']) || !$request_data['phone']) {
            return response()->json(['code' => 0, 'message' => '联系电话为必填项']);
        }
        if (!isset($request_data['verification_code']) || !$request_data['verification_code']) {
            return response()->json(['code' => 0, 'message' => '验证码为必填项']);
        }
        if (!isset($request_data['sex']) || !$request_data['sex']) {
            return response()->json(['code' => 0, 'message' => '性别为必填项']);
        }
        if (!isset($request_data['birthday']) || !$request_data['birthday']) {
            return response()->json(['code' => 0, 'message' => '出生日期为必填项']);
        }
        if (!isset($request_data['idcard']) || !$request_data['idcard']) {
            return response()->json(['code' => 0, 'message' => '身份证为必填项']);
        }
        if (!isset($request_data['nationality']) || !$request_data['nationality']) {
            return response()->json(['code' => 0, 'message' => '民族为必填项']);
        }
        if (!isset($request_data['birthplace']) || !$request_data['birthplace']) {
            return response()->json(['code' => 0, 'message' => '籍贯为必填项']);
        }
        // if (!isset($request_data['social_security']) || !$request_data['social_security']) {
        //     return response()->json(['code' => 0, 'message' => '社保参保地为必填项']);
        // }
        if (!isset($request_data['come_work_time']) || !$request_data['come_work_time']) {
            return response()->json(['code' => 0, 'message' => '来区工作时间为必填项']);
        }
        if (!isset($request_data['education']) || !$request_data['education']) {
            return response()->json(['code' => 0, 'message' => '学历为必填项']);
        }
        if (!isset($request_data['degree']) || !$request_data['degree']) {
            return response()->json(['code' => 0, 'message' => '学位为必填项']);
        }
        if (!isset($request_data['job_title']) || !$request_data['job_title']) {
            return response()->json(['code' => 0, 'message' => '职称为必填项']);
        }
        if (!isset($request_data['position']) || !$request_data['position']) {
            return response()->json(['code' => 0, 'message' => '职务为必填项']);
        }
        if (!isset($request_data['work_time']) || !$request_data['work_time']) {
            return response()->json(['code' => 0, 'message' => '任职时间为必填项']);
        }
        if (!isset($request_data['house_situation']) || !$request_data['house_situation']) {
            return response()->json(['code' => 0, 'message' => '住房情况为必填项']);
        }
        if (!isset($request_data['address']) || !$request_data['address']) {
            return response()->json(['code' => 0, 'message' => '详细地址为必填项']);
        }
        if (!isset($request_data['lease_period_start_time']) || !$request_data['lease_period_start_time']) {
            return response()->json(['code' => 0, 'message' => '开始租房时间为必填项']);
        }
        if (!isset($request_data['lease_period_end_time']) || !$request_data['lease_period_end_time']) {
            return response()->json(['code' => 0, 'message' => '结束租房时间为必填项']);
        }
        // if (!isset($request_data['study_work_experience']) || !$request_data['study_work_experience']) {
        //     return response()->json(['code' => 0, 'message' => '学习与工作经历为必填项']);
        // }
        if (!isset($request_data['photo']) || !$request_data['photo']) {
            return response()->json(['code' => 0, 'message' => '照片为必填项']);
        }
        if (!isset($request_data['marriage_childbirth']) || !$request_data['marriage_childbirth']) {
            return response()->json(['code' => 0, 'message' => '婚育情况为必填项']);
        }
        if (trim($request_data['marriage_childbirth']) != '未婚') {
	        if (!isset($request_data['spouse_name']) || !$request_data['spouse_name']) {
	            return response()->json(['code' => 0, 'message' => '配偶名称为必填项']);
	        }
	        if (!isset($request_data['spouse_idcard']) || !$request_data['spouse_idcard']) {
	            return response()->json(['code' => 0, 'message' => '配偶身份证为必填项']);
	        }
	        if (!isset($request_data['spouse_contact']) || !$request_data['spouse_contact']) {
	            return response()->json(['code' => 0, 'message' => '配偶联系方式为必填项']);
	        }
	        if (!isset($request_data['spouse_work_unit']) || !$request_data['spouse_work_unit']) {
	            return response()->json(['code' => 0, 'message' => '配偶工作单位为必填项']);
	        }
	        if (!isset($request_data['spouse_house_situation']) || !$request_data['spouse_house_situation']) {
	            return response()->json(['code' => 0, 'message' => '配偶住房情况为必填项']);
	        }
        }
        if (!isset($request_data['relevant_information']) || !$request_data['relevant_information']) {
            return response()->json(['code' => 0, 'message' => '相关资料为必填项']);
        }

        // 验证验证码
        $code = new NoteCodeController();
        $bool = $code->verifyCode(['code' => $request_data['verification_code'], 'mobile' => $request_data['phone']]);
        if($bool['code'] == 0){
            return $bool;
        }

        $user_id = $request_data['user']['uid'];
        $result = [];

        $field_list  = ['unit_name', 'unit_name_range','corporate_compliance','organization_code','unit_nature','field','contact_name','contact_phone','contact_address','talent_category','honor_level','honors','real_name','phone','sex','birthday','idcard','nationality','birthplace','social_security','come_work_time','education','degree','job_title','position','work_time','house_situation','address','lease_period_start_time','lease_period_end_time','study_work_experience','photo','marriage_childbirth','spouse_name','spouse_idcard','spouse_contact','spouse_work_unit','spouse_house_situation','relevant_information','file'];
        foreach ($field_list as $key => $value) {

            $data[$value] = isset($request_data[$value])?$request_data[$value]:'';
        }
        $data['user_id'] = $user_id;
        if (!isset($request_data['apartment_application_id']) || !$request_data['apartment_application_id']) {
            $application_info = DB::table('apartment_application')->where('user_id', $user_id)->first();
            if ($application_info) {
                return response()->json(['code' => 0, 'message' => '你已经申请公寓，可点击查询查看申请进度']);
            }
            DB::beginTransaction();
            try {
                $user_ids = (new RoleUser())->getRoleUsersByPermissionId(config('message')[50]['regulation']);
                $message = new MessageController();
                foreach ($user_ids as $key => $uid) {
                    $message->addMessage($uid->user_id, 50, '公寓申请待审核');
                }
                if ($user_id && DB::table('apartment_application')->insert($data)) {
                    DB::commit();
                    return response()->json(['code' => 1, 'message' => '申请成功']);
                } else {
                    DB::rollBack();
                    return response()->json(['code' => 0, 'message' => '申请失败']);
                }
            }  catch (Exception $e) {
                DB::rollBack();
                return response()->json(['code' => 0, 'message' => '申请失败']);
            }
        } else {
            $data['apartment_application_id'] = $request_data['apartment_application_id'];
            $data['approval_status'] = 0;
            $user_ids = (new RoleUser())->getRoleUsersByPermissionId(config('message')[50]['regulation']);
            $message = new MessageController();
            foreach ($user_ids as $key => $uid) {
                $message->addMessage($uid->user_id, 50, '公寓申请待审核');
            }
            if (DB::table('apartment_application')->where('apartment_application_id', trim($data['apartment_application_id']))->update($data)) {
                $result['code'] = 1;
                $result['message'] = '修改成功';
            } else {
                $result['code'] = 0;
                $result['message'] = '修改失败或内容没作修改';
            }
        }

        return response()->json($result);
	}

	public function renewalAppication(Request $request) {
        if (!$request->isMethod('POST')) {
            return response()->json(['code' => 0, 'message' => '提交方式错误']);
        }

        $request_data = $request->input();

        if (!isset($request_data['room_no_id']) || !$request_data['room_no_id']) {
            return response()->json(['code' => 0, 'message' => '房号ID为必填项']);
        }
        if (!isset($request_data['renewal_end_time']) || !$request_data['renewal_end_time']) {
            return response()->json(['code' => 0, 'message' => '续租截止时间为必填项']);
        }
        if (!isset($request_data['reason']) || !$request_data['reason']) {
            return response()->json(['code' => 0, 'message' => '理由为必填项']);
        }
        if (!isset($request_data['relevant_information']) || !$request_data['relevant_information']) {
            return response()->json(['code' => 0, 'message' => '相关资料为必填项']);
        }

        if (DB::table('renewal_appication')->where('room_no_id', $request_data['room_no_id'])->where('approval_status', 0)->first()) {
            return response()->json(['code' => 0, 'message' => '当前还有待审核记录，请勿重复提交']);
        }

        if (!DB::table('room_no')->where('room_no_id', $request_data['room_no_id'])->where('status', 1)->where('room_status', 2)->first()) {
            return response()->json(['code' => 0, 'message' => '请房屋入住后再来提交']);
        }

        unset($request_data['user']);
        $result = [];
        $data = array(
        	'room_no_id' => $request_data['room_no_id'],
        	'renewal_end_time' => $request_data['renewal_end_time'],
        	'reason' => $request_data['reason'],
        	'relevant_information' => $request_data['relevant_information']
        );
        $user_ids = (new RoleUser())->getRoleUsersByPermissionId(config('message')[60]['regulation']);
        $message = new MessageController();
        foreach ($user_ids as $key => $uid) {
            $message->addMessage($uid->user_id, 60, '有续租申请待处理');
        }
        if (DB::table('renewal_appication')->insert($data)) {
            $result['code'] = 1;
            $result['message'] = '提交成功';
        } else {
            $result['code'] = 0;
            $result['message'] = '提交失败';
        }
        return response()->json($result);
	}

	public function withdrawalAppication(Request $request) {
        if (!$request->isMethod('POST')) {
            return response()->json(['code' => 0, 'message' => '提交方式错误']);
        }

        $request_data = $request->input();

        if (!isset($request_data['room_no_id']) || !$request_data['room_no_id']) {
            return response()->json(['code' => 0, 'message' => '房号ID为必填项']);
        }
        if (!isset($request_data['withdrawal_time']) || !$request_data['withdrawal_time']) {
            return response()->json(['code' => 0, 'message' => '退租日期为必填项']);
        }
        if (!isset($request_data['reason']) || !$request_data['reason']) {
            return response()->json(['code' => 0, 'message' => '理由为必填项']);
        }

        if (DB::table('withdrawal_appication')->where('room_no_id', $request_data['room_no_id'])->where('approval_status', 0)->first()) {
            return response()->json(['code' => 0, 'message' => '当前还有待审核记录，请勿重复提交']);
        }

        if (!DB::table('room_no')->where('room_no_id', $request_data['room_no_id'])->where('status', 1)->where('room_status', 2)->first()) {
            return response()->json(['code' => 0, 'message' => '请房屋入住后再来提交']);
        }
        $apartment_application_info = DB::table('apartment_application')->where('user_id', $request_data['user']['uid'])->first();
        if (!$apartment_application_info) {
            return response()->json(['code' => 0, 'message' => '获取申请信息失败']);
        }
        unset($request_data['user']);
        $result = [];
        $data = array(
            'apartment_application_id' => $apartment_application_info->apartment_application_id,
        	'room_no_id' => $request_data['room_no_id'],
        	'withdrawal_time' => $request_data['withdrawal_time'],
        	'reason' => $request_data['reason']
        );
        $user_ids = (new RoleUser())->getRoleUsersByPermissionId(config('message')[61]['regulation']);
        $message = new MessageController();
        foreach ($user_ids as $key => $uid) {
            $message->addMessage($uid->user_id, 61, '有退租申请待处理');
        }
        if (DB::table('withdrawal_appication')->insert($data)) {
            $result['code'] = 1;
            $result['message'] = '提交成功';
        } else {
            $result['code'] = 0;
            $result['message'] = '提交失败';
        }
        return response()->json($result);
	}

	public function situationReflection(Request $request) {
        if (!$request->isMethod('POST')) {
            return response()->json(['code' => 0, 'message' => '提交方式错误']);
        }

        $request_data = $request->input();

        if (!isset($request_data['room_no_id']) || !$request_data['room_no_id']) {
            return response()->json(['code' => 0, 'message' => '房号ID为必填项']);
        }
        if (!isset($request_data['description']) || !$request_data['description']) {
            return response()->json(['code' => 0, 'message' => '说明为必填项']);
        }
        if (!isset($request_data['relevant_information']) || !$request_data['relevant_information']) {
            return response()->json(['code' => 0, 'message' => '照片为必填项']);
        }

        if (!DB::table('room_no')->where('room_no_id', $request_data['room_no_id'])->where('status', 1)->where('room_status', 2)->first()) {
            return response()->json(['code' => 0, 'message' => '请房屋入住后再来提交']);
        }
        $apartment_application_info = DB::table('apartment_application')->where('user_id', $request_data['user']['uid'])->first();
        if (!$apartment_application_info) {
            return response()->json(['code' => 0, 'message' => '获取申请信息失败']);
        }
        unset($request_data['user']);
        $result = [];
        $data = array(
            'apartment_application_id' => $apartment_application_info->apartment_application_id,
        	'room_no_id' => $request_data['room_no_id'],
        	'description' => $request_data['description'],
        	'relevant_information' => $request_data['relevant_information']
        );
        $user_ids = (new RoleUser())->getRoleUsersByPermissionId(config('message')[62]['regulation']);
        $message = new MessageController();
        foreach ($user_ids as $key => $uid) {
            $message->addMessage($uid->user_id, 62, '有情况反应待处理');
        }
        if (DB::table('situation_reflection')->insert($data)) {
            $result['code'] = 1;
            $result['message'] = '提交成功';
        } else {
            $result['code'] = 0;
            $result['message'] = '提交失败';
        }
        return response()->json($result);
	}

	public function schedule(Request $request) {
        $request_data = $request->input();
        $user_id = $request_data['user']['uid'];
        $apartment_application_info = DB::table('apartment_application')->where('user_id', $user_id)->first();
        if (!$apartment_application_info) {
            return response()->json(['code' => 0, 'message' => '你还没有提交申请']);
        }
        $response_data = [];
        if ($apartment_application_info->approval_status == 4) {
            $approval_info = DB::table('apartment_approval_records')->where('apartment_application_id', $apartment_application_info->apartment_application_id)->where('stage', 2)->where('approval_result', 1)->orderby('apartment_approval_record_id', 'DESC')->first();
            $response_data = array(
                'approval_result' => 4,
                'approval_time' => $approval_info->add_time,
                'remark' => $approval_info->remark,
                'is_distribution' => 0,
                'give_up_info' => [],
                'confirm_info' => []
            );
        	$room_no_info = DB::table('room_no')->where('apartment_application_id', $apartment_application_info->apartment_application_id)->first();
            if (!$room_no_info) {
                $house_operate_records_info = DB::table('house_operate_records')->where('apartment_application_id', $apartment_application_info->apartment_application_id)->orderby('add_time', 'desc')->first();
                if ($house_operate_records_info) {
                    $room_no_info = DB::table('room_no')->where('room_no_id', $house_operate_records_info->room_no_id)->first();
                }
            }
        	if ($room_no_info) {
                $community_info = DB::table('community')->where('community_id', $room_no_info->community_id)->first();
                $building_info = DB::table('building')->where('building_id', $room_no_info->building_id)->first();
                $house_type_info = DB::table('house_type')->where('house_type_id', $room_no_info->house_type_id)->first();
                $response_data['hosue'] = $community_info->community_name.$building_info->buildings.$building_info->unit.$room_no_info->units.'单元'.$room_no_info->floors.'楼'.$room_no_info->room_no;
                $response_data['construction_area'] = $house_type_info->construction_area;
                $response_data['house_type'] = $house_type_info->rooms."室".$house_type_info->halls."厅".$house_type_info->guards."卫";
                $response_data['address'] = $community_info->province.$community_info->city.$community_info->area.$community_info->address;
                $response_data['is_distribution'] = 1;
                $house_operate_records_info = DB::table('house_operate_records')->where('apartment_application_id', $apartment_application_info->apartment_application_id)->where('room_no_id', $room_no_info->room_no_id)->where('operate_status', 0)->first();
                if ($house_operate_records_info) {
                    $response_data['remark'] = $house_operate_records_info->remark;
                }
                $response_data['room_no_id'] = $room_no_info->room_no_id;
                // 确认入住信息
                if ($room_no_info->room_status == 2) {
                    $house_operate_records_info = DB::table('house_operate_records')->where('apartment_application_id', $apartment_application_info->apartment_application_id)->where('operate_status', 3)->orderby('add_time', 'desc')->first();
                    if ($house_operate_records_info) {
                        $response_data['confirm_info'] = array(
                            'remark' => '管理员已确认已入住',
                            'time' => $house_operate_records_info->add_time
                        );
                    }
                } else {
                    $house_operate_records_info = DB::table('house_operate_records')->where('apartment_application_id', $apartment_application_info->apartment_application_id)->where('operate_status', 1)->orderby('add_time', 'desc')->first();
                    if ($house_operate_records_info) {
                        $response_data['give_up_info'] = array(
                            'remark' => $house_operate_records_info->remark,
                            'time' => $house_operate_records_info->add_time
                        );
                        if ($house_operate_records_info->operate_uid) {
                            $response_data['confirm_info'] = array(
                                'remark' => '管理员已确认放弃入住',
                                'time' => $house_operate_records_info->modify_time
                            );
                        }
                    }
                }
        	}
        } else {
        	$approval_result = $apartment_application_info->approval_status;
        	$approval_info = '';
            $expired_desc = '';
        	if ($apartment_application_info->approval_status < 2) {
        		if ($apartment_application_info->approval_status == 1) {
        			$approval_info = DB::table('apartment_approval_records')->where('apartment_application_id', $apartment_application_info->apartment_application_id)->where('stage', 1)->where('approval_result', 1)->orderby('apartment_approval_record_id', 'DESC')->first();
        		}
        	} else if ($apartment_application_info->approval_status == 2 || $apartment_application_info->approval_status == 5) {
        		$approval_info = DB::table('apartment_approval_records')->where('apartment_application_id', $apartment_application_info->apartment_application_id)->where('approval_result', 0)->orderby('apartment_approval_record_id', 'DESC')->first();
                $expired_desc = date("Y-m-d",strtotime("+$approval_info->expired_days day",strtotime($approval_info->add_time))) . '日以后可再次提交申请';
        	} else if ($apartment_application_info->approval_status == 3 || $apartment_application_info->approval_status == 6) {
        		$approval_info = DB::table('apartment_approval_records')->where('apartment_application_id', $apartment_application_info->apartment_application_id)->where('approval_result', 2)->orderby('apartment_approval_record_id', 'DESC')->first();
        	}
    		$response_data = array(
        		'approval_result' => $approval_result,
        		'approval_time' => $approval_info ? $approval_info->add_time : '',
        		'remark' => $approval_info ? $approval_info->remark : '',
                'expired_desc' => $expired_desc
    		);
        }
        return response()->json(['code' => 1, 'data' => $response_data]);
	}

	public function renewalInfo(Request $request) {
        $request_data = $request->input();
        $user_id = $request_data['user']['uid'];
        $apartment_application_info = DB::table('apartment_application')->where('user_id', $user_id)->first();
        if (!$apartment_application_info) {
            // return response()->json(['code' => 0, 'message' => '你还没有提交公寓申请']);
            return response()->json(['code' => 1, 'data' => []]);
        }
        $room_no_info = DB::table('room_no')->where('apartment_application_id', $apartment_application_info->apartment_application_id)->first();
    	if (!$room_no_info) {
        	// return response()->json(['code' => 0, 'message' => '您还未分配房源，暂时不能进行续租申请操作']);
            return response()->json(['code' => 1, 'data' => []]);
    	}
        // 还未入住
        if ($room_no_info->room_status != 2) {
            return response()->json(['code' => 1, 'data' => []]);
        }
        $community_info = DB::table('community')->where('community_id', $room_no_info->community_id)->first();
        $building_info = DB::table('building')->where('building_id', $room_no_info->building_id)->first();
        $house_type_info = DB::table('house_type')->where('house_type_id', $room_no_info->house_type_id)->first();
        $response_data = array(
        	'room_no_id' => $room_no_info->room_no_id,
	    	'hosue' => $community_info->community_name.$building_info->buildings.$building_info->unit.$room_no_info->units.'单元'.$room_no_info->floors.'楼'.$room_no_info->room_no,
	    	'construction_area' => $house_type_info->construction_area,
	    	'house_type' => $house_type_info->rooms."室".$house_type_info->halls."厅".$house_type_info->guards."卫",
	    	'address' => $community_info->province.$community_info->city.$community_info->area.$community_info->address,
	    	'lease_period_start_time' => $room_no_info->lease_period_start_time,
	    	'lease_period_end_time' => $room_no_info->lease_period_end_time,
	    	'renewal_appications' => []
	    );
        $renewal_appications = DB::table('renewal_appication')->where('room_no_id', $room_no_info->room_no_id)->orderby('add_time', 'DESC')->get();
        foreach ($renewal_appications as $key => $value) {
        	array_push($response_data['renewal_appications'], array(
        		'application_time' => $value->add_time,
        		'renewal_end_time' => $value->renewal_end_time,
        		'approval_status' => $value->approval_status
        	));
        }
        return response()->json(['code' => 1, 'data' => $response_data]);
	}

	public function withdrawalInfo(Request $request) {
        $request_data = $request->input();
        $user_id = $request_data['user']['uid'];
        $apartment_application_info = DB::table('apartment_application')->where('user_id', $user_id)->first();
        if (!$apartment_application_info) {
            // return response()->json(['code' => 0, 'message' => '你还没有提交公寓申请']);
            return response()->json(['code' => 1, 'data' => []]);
        }
        $room_no_info = DB::table('room_no')->where('apartment_application_id', $apartment_application_info->apartment_application_id)->first();
    	if (!$room_no_info) {
        	// return response()->json(['code' => 0, 'message' => '您还未分配房源，暂时不能进行退租申请操作']);
            return response()->json(['code' => 1, 'data' => []]);
    	}
        // 还未入住
        if ($room_no_info->room_status != 2) {
            return response()->json(['code' => 1, 'data' => []]);
        }
        $community_info = DB::table('community')->where('community_id', $room_no_info->community_id)->first();
        $building_info = DB::table('building')->where('building_id', $room_no_info->building_id)->first();
        $house_type_info = DB::table('house_type')->where('house_type_id', $room_no_info->house_type_id)->first();
        $response_data = array(
        	'room_no_id' => $room_no_info->room_no_id,
	    	'hosue' => $community_info->community_name.$building_info->buildings.$building_info->unit.$room_no_info->units.'单元'.$room_no_info->floors.'楼'.$room_no_info->room_no,
	    	'construction_area' => $house_type_info->construction_area,
	    	'house_type' => $house_type_info->rooms."室".$house_type_info->halls."厅".$house_type_info->guards."卫",
	    	'address' => $community_info->province.$community_info->city.$community_info->area.$community_info->address,
	    	'lease_period_start_time' => $room_no_info->lease_period_start_time,
	    	'lease_period_end_time' => $room_no_info->lease_period_end_time,
	    	'renewal_appications' => []
	    );
        $renewal_appications = DB::table('withdrawal_appication')->where('room_no_id', $room_no_info->room_no_id)->orderby('add_time', 'DESC')->get();
        foreach ($renewal_appications as $key => $value) {
        	array_push($response_data['renewal_appications'], array(
        		'application_time' => $value->add_time,
        		'withdrawal_time' => $value->withdrawal_time,
        		'approval_status' => $value->approval_status
        	));
        }
        return response()->json(['code' => 1, 'data' => $response_data]);
	}

	public function situationReflectionInfo(Request $request) {
        $request_data = $request->input();
        $user_id = $request_data['user']['uid'];
        $apartment_application_info = DB::table('apartment_application')->where('user_id', $user_id)->first();
        if (!$apartment_application_info) {
            // return response()->json(['code' => 0, 'message' => '你还没有提交公寓申请']);
            return response()->json(['code' => 1, 'data' => []]);
        }
        $room_no_info = DB::table('room_no')->where('apartment_application_id', $apartment_application_info->apartment_application_id)->first();
    	if (!$room_no_info) {
        	// return response()->json(['code' => 0, 'message' => '您还未分配房源，暂时不能进行情况反应申请操作']);
            return response()->json(['code' => 1, 'data' => []]);
    	}
        // 还未入住
        if ($room_no_info->room_status != 2) {
            return response()->json(['code' => 1, 'data' => []]);
        }
        $community_info = DB::table('community')->where('community_id', $room_no_info->community_id)->first();
        $building_info = DB::table('building')->where('building_id', $room_no_info->building_id)->first();
        $house_type_info = DB::table('house_type')->where('house_type_id', $room_no_info->house_type_id)->first();
        $response_data = array(
        	'room_no_id' => $room_no_info->room_no_id,
	    	'hosue' => $community_info->community_name.$building_info->buildings.$building_info->unit.$room_no_info->units.'单元'.$room_no_info->floors.'楼'.$room_no_info->room_no,
	    	'construction_area' => $house_type_info->construction_area,
	    	'house_type' => $house_type_info->rooms."室".$house_type_info->halls."厅".$house_type_info->guards."卫",
	    	'address' => $community_info->province.$community_info->city.$community_info->area.$community_info->address,
	    	'lease_period_start_time' => $room_no_info->lease_period_start_time,
	    	'lease_period_end_time' => $room_no_info->lease_period_end_time,
	    	'renewal_appications' => []
	    );
        $renewal_appications = DB::table('situation_reflection')->where('room_no_id', $room_no_info->room_no_id)->orderby('add_time', 'DESC')->get();
        foreach ($renewal_appications as $key => $value) {
        	array_push($response_data['renewal_appications'], array(
        		'application_time' => $value->add_time,
        		'description' => $value->description,
        		'handle_status' => $value->handle_status
        	));
        }
        return response()->json(['code' => 1, 'data' => $response_data]);
	}

    public function apartmentApplicationInfo(Request $request) {
        $request_data = $request->input();
        $user_id = $request_data['user']['uid'];
        $apartment_application_info = DB::table('apartment_application')->where('user_id', $user_id)->first();
        if (!$apartment_application_info) {
            return response()->json(['code' => 0, 'message' => '你还没有提交公寓申请']);
        }
        return response()->json(['code' => 1, 'data' => $apartment_application_info]);
    }

    public function apartmentApplicationStatus(Request $request) {
        $request_data = $request->input();
        $user_id = $request_data['user']['uid'];
        // 0：未申请，1：已申请、不能重新提交申请，2：已申请、能重新提交申请
        $status = 0;
        $apartment_application_info = DB::table('apartment_application')->where('user_id', $user_id)->first();
        if ($apartment_application_info) {
            $status = 1;
            // 驳回可重新提交申请
            if ($apartment_application_info->approval_status == 3 || $apartment_application_info->approval_status == 6) {
                $status = 2;
            } elseif ($apartment_application_info->approval_status == 2 || $apartment_application_info->approval_status == 5) {
                $apartment_approval_records = DB::table('apartment_approval_records')->where('apartment_application_id', $apartment_application_info->apartment_application_id)->where('approval_result', '0')->orderby('apartment_approval_record_id', 'DESC')->first();
                if ($apartment_approval_records) {
                    if (date('Y-m-d H:i:s') > date("Y-m-d H:i:s",strtotime("+$apartment_approval_records->expired_days day",strtotime($apartment_approval_records->add_time)))) {
                        $status = 2;
                    }
                }
            }
        }
        return response()->json(['code' => 1, 'data' => ['status' => $status]]);
    }

    public function giveUpApplication(Request $request) {
        $request_data = $request->input();
        if (!isset($request_data['room_no_id']) || !$request_data['room_no_id']) {
            return response()->json(['code' => 0, 'message' => '房号ID为必填项']);
        }
        if (!isset($request_data['remark']) || !$request_data['remark']) {
            return response()->json(['code' => 0, 'message' => '原因为必填项']);
        }
        $room_no_info = DB::table('room_no')->where('room_no_id', $request_data['room_no_id'])->first();
        if (!$room_no_info) {
            return response()->json(['code' => 0, 'message' => '获取房源信息失败']);
        }

        DB::beginTransaction();
        try {
            $room_no_id = trim($request_data['room_no_id']);
            $house_operate_records_data = array(
                'room_no_id' => $room_no_id,
                'operate_status' => 1,
                'apartment_application_id' => $room_no_info->apartment_application_id,
                'remark' => $request_data['remark'],
                'operate_uid' => 0
            );
            if (DB::table('apartment_application')->where('apartment_application_id', $room_no_info->apartment_application_id)->update(array('is_give_up' => 1)) && DB::table('house_operate_records')->insert($house_operate_records_data)) {
                DB::commit();
                return response()->json(['code' => 1, 'message' => '操作成功']);
           } else {
                DB::rollBack();
                return response()->json(['code' => 0, 'message' => '操作失败']);
            }
        }  catch (Exception $e) {
            DB::rollBack();
            return response()->json(['code' => 0, 'message' => '操作失败']);
        } 
    }

    public function changeRoomApplication(Request $request) {
        $request_data = $request->input();
        if (!isset($request_data['room_no_id']) || !$request_data['room_no_id']) {
            return response()->json(['code' => 0, 'message' => '房号ID为必填项']);
        }
        if (!isset($request_data['remark']) || !$request_data['remark']) {
            return response()->json(['code' => 0, 'message' => '换房理由为必填项']);
        }
        if (!isset($request_data['photos']) || !$request_data['photos']) {
            return response()->json(['code' => 0, 'message' => '照片为必填项']);
        }
        $room_no_info = DB::table('room_no')->where('room_no_id', $request_data['room_no_id'])->first();
        if (!$room_no_info) {
            return response()->json(['code' => 0, 'message' => '获取房源信息失败']);
        }
        if (!DB::table('apartment_application')->where('user_id', $request_data['user']['uid'])->where('apartment_application_id', $room_no_info->apartment_application_id)->where('is_give_up', 0)->first()) {
            return response()->json(['code' => 0, 'message' => '您不符合换房条件']);
        }

        if (DB::table('change_room_application_records')->where('room_no_id', $request_data['room_no_id'])->where('approval_status', 0)->first()) {
            return response()->json(['code' => 0, 'message' => '您有未审核换房申请，请勿重复提交']);
        }

        DB::beginTransaction();
        try {
            $room_no_id = trim($request_data['room_no_id']);
            $change_room_application_records_data = array(
                'room_no_id' => $room_no_id,
                'apartment_application_id' => $room_no_info->apartment_application_id,
                'remark' => $request_data['remark'],
                'photos' => $request_data['photos']
            );
            if (DB::table('change_room_application_records')->insert($change_room_application_records_data)) {
                DB::commit();
                return response()->json(['code' => 1, 'message' => '操作成功']);
           } else {
                DB::rollBack();
                return response()->json(['code' => 0, 'message' => '操作失败']);
            }
        }  catch (Exception $e) {
            DB::rollBack();
            return response()->json(['code' => 0, 'message' => '操作失败']);
        } 
    }

    public function changeRoomInfo(Request $request) {
        $request_data = $request->input();
        $user_id = $request_data['user']['uid'];
        $apartment_application_info = DB::table('apartment_application')->where('user_id', $user_id)->first();
        if (!$apartment_application_info) {
            return response()->json(['code' => 0, 'message' => '您还没有提交公寓申请']);
        }
        if ($apartment_application_info->is_give_up == 1) {
            return response()->json(['code' => 0, 'message' => '您还没有提交公寓申请']);
        }
        $room_no_info = DB::table('room_no')->where('apartment_application_id', $apartment_application_info->apartment_application_id)->first();
        if (!$room_no_info) {
            return response()->json(['code' => 0, 'message' => '您还未分配房源，暂时不能进行换房申请']);
        }
        // 还未入住
        if ($room_no_info->room_status != 2) {
            return response()->json(['code' => 0, 'message' => '您还未入住房源，暂时不能进行情况反应申请操作']);
        }
        $community_info = DB::table('community')->where('community_id', $room_no_info->community_id)->first();
        $building_info = DB::table('building')->where('building_id', $room_no_info->building_id)->first();
        $house_type_info = DB::table('house_type')->where('house_type_id', $room_no_info->house_type_id)->first();
        $response_data = array(
            'room_no_id' => $room_no_info->room_no_id,
            'hosue' => $community_info->community_name.$building_info->buildings.$building_info->unit.$room_no_info->units.'单元'.$room_no_info->floors.'楼'.$room_no_info->room_no,
            'construction_area' => $house_type_info->construction_area,
            'house_type' => $house_type_info->rooms."室".$house_type_info->halls."厅".$house_type_info->guards."卫",
            'address' => $community_info->province.$community_info->city.$community_info->area.$community_info->address,
            'change_room_records' => []
        );
        $sql = "SELECT rh.remark, rh.photos, rh.add_time, rh.modify_time, rh.room_no_id, rh.new_room_no_id, rh.approval_status, rh.approval_reason FROM rcjh_room_no rr, rcjh_apartment_application ra, rcjh_change_room_application_records rh WHERE rh.apartment_application_id = ra.apartment_application_id AND rh.apartment_application_id = rr.apartment_application_id AND ra.user_id = ".$request_data['user']['uid']." ORDER BY rh.modify_time DESC";
        $response_data['change_room_records'] = DB::table(DB::raw("($sql limit 9999999) as rcjh_room_no"))->get();
        foreach ($response_data['change_room_records'] as $key => $value) {
            if ($value->room_no_id) {
                $room_no_info = DB::table('room_no')->where('room_no_id', $value->room_no_id)->first();
                if ($room_no_info) {
                    $community_info = DB::table('community')->where('community_id', $room_no_info->community_id)->first();
                    $building_info = DB::table('building')->where('building_id', $room_no_info->building_id)->first();
                    $response_data['change_room_records'][$key]->hosue = $community_info->community_name.$building_info->buildings.$building_info->unit.$room_no_info->units.'单元'.$room_no_info->floors.'楼'.$room_no_info->room_no;
                }
            }
            if ($value->new_room_no_id) {
                $room_no_info = DB::table('room_no')->where('room_no_id', $value->new_room_no_id)->first();
                if ($room_no_info) {
                    $community_info = DB::table('community')->where('community_id', $room_no_info->community_id)->first();
                    $building_info = DB::table('building')->where('building_id', $room_no_info->building_id)->first();
                    $response_data['change_room_records'][$key]->new_hosue = $community_info->community_name.$building_info->buildings.$building_info->unit.$room_no_info->units.'单元'.$room_no_info->floors.'楼'.$room_no_info->room_no;
                }
            }
        }
        return response()->json(['code' => 1, 'data' => $response_data]);
    }
}